<template>
  <div :class="{ fullscreen: fullscreen }"
       class="tinymce-container"
       :style="{ width: containerWidth }">
    <textarea :id="tinymceId"
              class="tinymce-textarea" />
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff"
                   class="editor-upload-btn"
                   @successCBK="imageSuccessCBK" />
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.gitee.io/vue-element-admin-site/zh/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import API from '@/api'

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
const tinymceCDN =
  'https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.0.2/tinymce.min.js'

export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default () {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    baseUrl: {
      type: String,
      default: window.location.origin ? window.location.origin : ''
    }
  },
  data () {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false
    }
  },
  computed: {
    containerWidth () {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value (val) {
      if (!val) this.hasChange = false
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || '')
        )
      }
    }
  },
  mounted () {
    this.init()
  },
  activated () {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated () {
    this.destroyTinymce()
  },
  destroyed () {
    this.destroyTinymce()
  },
  methods: {
    init () {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    initTinymce () {
      console.log('init')
      const _this = this
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        language_url: `${this.baseUrl}/tinymce/langs/zh-Hans.js`,
        language: 'zh-Hans',
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        // menubar: this.menubar,
        menubar: false,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        // imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true,
        images_upload_url: 'https://files.meta-720.com/demo/upimg.php', // 图片上传API
        branding: false,
        // 初始化结束后执行
        init_instance_callback: (editor) => {
          if (this.value) {
            editor.setContent(this.value)
          }
          this.hasInit = true
          editor.on('NodeChange Change KeyUp', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup (editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        convert_urls: false,
        // 自定义图片拖拽上传
        images_upload_handler (blobInfo, progress) {
          console.log('触发')
          progress(0)
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          // return API.pushRichFile(formData)
          //   .then(({ data }) => (progress(100), data.file))
          //   .catch(
          //     (err) => (
          //       console.dir(err),
          //       Promise.reject("出现未知问题，刷新页面，或者联系程序员")
          //     )
          //   );
          formData.append('app_key', 'weilai')
          formData.append('source_type', '2')
          this.$http.post(`https://files.meta-720.com/upload/v1/`, formData)
            .then(({ data }) => (progress(100), data.files[0].source_path)
            ).catch(() => {
              (err) => (
                Promise.reject('出现未知问题，刷新页面，或者联系程序员')
              )
            })
        },
        // file_picker_types: "file image media",
        // 文件上传回调（文件、图片、视频）
        file_picker_callback: function (callback, value, meta) {
          // 文件分类
          var filetype =
            '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4'
          // 为不同插件指定文件类型及后端地址
          switch (meta.filetype) {
            case 'image':
              filetype = '.jpg, .jpeg, .png, .gif'
              break
            case 'media':
              filetype = '.mp3, .mp4'
              break
            case 'file':
            default:
          }
          // 模拟出一个input用于添加本地文件
          var input = document.createElement('input')
          input.setAttribute('type', 'file')
          input.setAttribute('accept', filetype)
          input.click()
          input.onchange = function () {
            console.log('change')
            const file = this.files[0]
            const formData = new FormData()
            formData.append('file', file)
            formData.append('app_key', 'weilai')
            formData.append('source_type', '2')
            API.pushRichFile(formData)
              .then(({ data }) => {
                callback(data.files[0].source_path)
              }).catch()
          }
        }
      })
    },
    destroyTinymce () {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.off('NodeChange Change KeyUp SetContent')
        // tinymce.destroy();
      }
    },
    setContent (value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent () {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK (arr) {
      arr.forEach((v) =>
        window.tinymce
          .get(this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`)
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}
</style>
